# -*- coding: utf-8 -*-
"""
# @created on : 9月 2021/9/26 09:08
# @author     : kevin
# @file       : mail.py
# @software   : PyCharm
# @project    : auto_keyword_data


@license: (C) Copyright 2019-2025, Corporation Limited.
@desc:发送邮件配置
"""
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from utils.ini import OperationIni
import os
from common.log import Logger


class SendMail:
    def __init__(self, **kwargs):
        self.oi = OperationIni()
        self.log = Logger()
        self.user = self.oi.read_cfg('mail', 'user')
        self.pwd = self.oi.read_cfg('mail', 'pwd')
        self.send_to = self.oi.read_cfg('mail', 'send_to')
        self.host = self.oi.read_cfg('mail', 'host')
        self.port = self.oi.read_cfg('mail', 'port')

    def send_mail(self, **kwargs):
        file = kwargs.get('file')
        msg = kwargs.get('msg')
        message = MIMEMultipart()
        message.attach(MIMEText(msg, _subtype='plain', _charset='utf-8'))
        message['FROM'] = self.user
        message['To'] = self.send_to
        message['subject'] = kwargs.get('sub')

        if file:
            file_name = str(os.path.basename(file))
            attr = MIMEApplication(open(file, 'rb').read())
            attr.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file_name))
            message.attach(attr)

        try:
            smtp_obj = smtplib.SMTP(host=self.host, port=self.port)
            smtp_obj.login(user=self.user, password=self.pwd)
            smtp_obj.sendmail(self.user, self.send_to, str(message))
            self.log.logger('info', '发送邮件成功')

        except SyntaxError as e:
            self.log.logger('error', e)
            print(e)
        finally:
            smtp_obj.quit()
